<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="90px" size="small" v-show="showSearch">
      <el-form-item label="仓库" prop="warehouseId">
        <el-select v-model="queryParams.warehouseId" placeholder="请选择仓库" clearable filterable @change="handleWarehouseChange">
          <el-option v-for="item in warehouseOptions" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="库区" prop="zoneId">
        <el-select v-model="queryParams.zoneId" placeholder="请选择库区" clearable filterable>
          <el-option v-for="item in zoneOptions" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="货位编码" prop="code">
        <el-input v-model="queryParams.code" placeholder="请输入货位编码" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['wms:location:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                   v-hasPermi="['wms:location:edit']">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                   v-hasPermi="['wms:location:remove']">删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   v-hasPermi="['wms:location:export']">导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"/>
    </el-row>

    <el-table v-loading="loading" :data="locationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="货位编码" prop="code" width="140"/>
      <el-table-column label="货位名称" prop="name" width="160"/>
      <el-table-column label="所属仓库" prop="warehouseId" width="160">
        <template #default="scope">
          <span>{{ getWarehouseName(scope.row.warehouseId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属库区" prop="zoneId" width="160">
        <template #default="scope">
          <span>{{ getZoneName(scope.row.zoneId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="货位类型" prop="locationType" width="120"/>
      <el-table-column label="允许混放" prop="mixSkuFlag" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.mixSkuFlag === 1 ? 'success' : 'info'">{{ scope.row.mixSkuFlag === 1 ? '是' : '否' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="锁定" prop="lockedFlag" width="90">
        <template #default="scope">
          <el-switch v-model="scope.row.lockedFlag" disabled :active-value="1" :inactive-value="0"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status" width="90">
        <template #default="scope">
          <dict-tag :options="dict.type.CommDataStatus" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template #default="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['wms:location:edit']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['wms:location:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="所属仓库" prop="warehouseId">
              <el-select v-model="form.warehouseId" placeholder="请选择仓库" filterable clearable @change="loadZoneOptions">
                <el-option v-for="item in warehouseOptions" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属库区" prop="zoneId">
              <el-select v-model="form.zoneId" placeholder="请选择库区" filterable clearable>
                <el-option v-for="item in dialogZoneOptions" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="货位编码" prop="code">
              <el-input v-model="form.code" placeholder="请输入货位编码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="货位名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入货位名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="货位类型" prop="locationType">
              <el-input v-model="form.locationType" placeholder="请输入货位类型"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最大数量" prop="maxQuantity">
              <el-input-number v-model="form.maxQuantity" :min="0" controls-position="right" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最大体积" prop="maxVolume">
              <el-input-number v-model="form.maxVolume" :min="0" :precision="2" :step="0.1" controls-position="right"
                               style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最大重量" prop="maxWeight">
              <el-input-number v-model="form.maxWeight" :min="0" :precision="2" :step="0.1" controls-position="right"
                               style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="允许混放" prop="mixSkuFlag">
              <el-switch v-model="form.mixSkuFlag" :active-value="1" :inactive-value="0"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="锁定" prop="lockedFlag">
              <el-switch v-model="form.lockedFlag" :active-value="1" :inactive-value="0"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in dict.type.CommDataStatus" :key="dict.value"
                          :label="parseInt(dict.value)">{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="description">
              <el-input type="textarea" v-model="form.description" placeholder="请输入备注" :rows="3"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listWarehouse} from '@/api/wms/warehouse'
import {listZone} from '@/api/wms/zone'
import {addLocation, delLocation, getLocation, listLocation, updateLocation} from '@/api/wms/location'

export default {
  name: 'WmsLocation',
  dicts: ['CommDataStatus'],
  data() {
    return {
      loading: false,
      showSearch: true,
      total: 0,
      locationList: [],
      warehouseOptions: [],
      zoneOptions: [],
      dialogZoneOptions: [],
      ids: [],
      single: true,
      multiple: true,
      open: false,
      title: '',
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        warehouseId: undefined,
        zoneId: undefined,
        code: undefined
      },
      form: {},
      rules: {
        warehouseId: [{required: true, message: '请选择仓库', trigger: 'change'}],
        zoneId: [{required: true, message: '请选择库区', trigger: 'change'}],
        code: [{required: true, message: '货位编码不能为空', trigger: 'blur'}],
        name: [{required: true, message: '货位名称不能为空', trigger: 'blur'}],
        status: [{required: true, message: '请选择状态', trigger: 'change'}]
      }
    }
  },
  created() {
    this.loadWarehouses()
    this.getList()
  },
  methods: {
    loadWarehouses() {
      listWarehouse({pageNum: 1, pageSize: 9999}).then(res => {
        this.warehouseOptions = res.rows || []
      })
    },
    loadZoneOptions(warehouseId) {
      if (!warehouseId) {
        this.dialogZoneOptions = []
        return
      }
      listZone({pageNum: 1, pageSize: 9999, warehouseId}).then(res => {
        this.dialogZoneOptions = res.rows || []
      })
    },
    handleWarehouseChange(val) {
      this.queryParams.zoneId = undefined
      if (val) {
        listZone({pageNum: 1, pageSize: 9999, warehouseId: val}).then(res => {
          this.zoneOptions = res.rows || []
        })
      } else {
        this.zoneOptions = []
      }
    },
    getList() {
      this.loading = true
      listLocation(this.queryParams).then(res => {
        this.locationList = res.rows || []
        this.total = res.total || 0
        this.loading = false
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    getWarehouseName(id) {
      const target = this.warehouseOptions.find(item => item.id === id)
      return target ? target.name : id
    },
    getZoneName(id) {
      const target = [...this.zoneOptions, ...this.dialogZoneOptions].find(item => item.id === id)
      return target ? target.name : id
    },
    reset() {
      this.form = {
        id: undefined,
        warehouseId: undefined,
        zoneId: undefined,
        code: undefined,
        name: undefined,
        locationType: undefined,
        maxQuantity: undefined,
        maxVolume: undefined,
        maxWeight: undefined,
        mixSkuFlag: 1,
        lockedFlag: 0,
        description: undefined,
        status: 1
      }
      this.dialogZoneOptions = []
      this.resetForm('form')
    },
    cancel() {
      this.open = false
      this.reset()
    },
    handleAdd() {
      this.reset()
      if (this.queryParams.warehouseId) {
        this.form.warehouseId = this.queryParams.warehouseId
        this.loadZoneOptions(this.form.warehouseId)
      }
      this.open = true
      this.title = '新增货位'
    },
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids[0]
      getLocation(id).then(res => {
        this.form = res.data
        if (this.form.mixSkuFlag === null) this.form.mixSkuFlag = 1
        if (this.form.lockedFlag === null) this.form.lockedFlag = 0
        this.loadZoneOptions(this.form.warehouseId)
        this.open = true
        this.title = '修改货位'
      })
    },
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (!valid) return
        const request = this.form.id ? updateLocation(this.form) : addLocation(this.form)
        request.then(() => {
          this.$modal.msgSuccess('保存成功')
          this.open = false
          this.getList()
        })
      })
    },
    handleDelete(row) {
      const ids = row.id ? [row.id] : this.ids
      this.$modal.confirm('是否确认删除选中的货位？').then(() => delLocation(ids.join(','))).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    handleExport() {
      this.download('/wms/location/export', {...this.queryParams}, `location_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

